package com.yuanli.cosmeticmirror.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;


import com.orhanobut.logger.Logger;
import com.yuanli.cosmeticmirror.base.Config;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

import kotlin.jvm.internal.Intrinsics;

import static com.mob.tools.utils.FileUtils.getFileByPath;


public class FileUtils {
    public FileUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 创建文件
     *
     * @param paramString
     * @return
     */
    public static String createFile(String paramString) {
        File localFile = new File(paramString);
        if (localFile.exists()) {
            localFile.delete();
        }
        try {
            localFile.createNewFile();
        } catch (IOException localIOException) {
            localIOException.printStackTrace();
        }
        return localFile.getAbsolutePath();
    }

    /**
     * 判断文件是否存在
     */
    public static boolean fileIsExists(String filePath) {
        if (filePath != null) {
            try {
                File f = new File(filePath);
                return f.exists() && f.isFile();
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }

    public static String getRealFilePath(final Context context, final Uri uri) {
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns
                    .DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 创建文件夹
     *
     * @param paramString
     */
    public static void createFolder(String paramString) {
        File file = null;
        try {
            StringBuilder pathStringBuilder = new StringBuilder();
            pathStringBuilder.append(getSDCardRoot());
            String[] fPath = paramString.split("/");
            for (int i = 0; i < fPath.length; i++) {
                if (fPath[i].isEmpty()) {
                    continue;
                }
                pathStringBuilder.append("/");
                pathStringBuilder.append(fPath[i]);
                String filePath = pathStringBuilder.toString();
                file = new File(filePath);
                if (!file.exists()) {
                    if (file.mkdir()) {
                        //                        LogUtils.v("创建成功：" + filePath);
                    } else {
                        //                        LogUtils.v("创建失败：" + filePath);
                    }
                }
            }
        } catch (Exception e) {
            //            LogUtils.i(e + "");
        }
    }

    /**
     * 创建目录
     *
     * @param path
     */
    public static void createDirs(String path) {
        // 新建一个File，传入文件夹目录
        File file = new File(path);
        // 判断文件夹是否存在，如果不存在就创建，否则不创建
        if (!file.exists()) {
            // 通过file的mkdirs()方法创建目录中包含却不存在的文件夹
            file.mkdirs();
        }
    }


    /**
     * 创建文件夹和文件
     *
     * @param paramString1
     * @param paramString2
     * @return
     */
    public static String createMkdirsAndFiles(String paramString1, String paramString2) {

        StringBuilder pathStringBuilder = new StringBuilder();
        pathStringBuilder.append(getSDCardRoot());
        pathStringBuilder.append(paramString1);
        pathStringBuilder.append("/");
        pathStringBuilder.append(paramString2);
        File file = new File(pathStringBuilder.toString());
        if (file.exists()) {
            return file.getPath();
        } else {
            //创建文件夹
            createFolder(paramString1);
            //创建文件
            return createFile(pathStringBuilder.toString());
        }
    }

    /**
     * 删除所有文件
     *
     * @param paramString
     * @param paramBoolean
     * @return
     */
    public static boolean deleteAllFile(String paramString, boolean paramBoolean) {
        if (!TextUtils.isEmpty(paramString)) {
        }
        for (; ; ) {
            int j;
            try {
                File localFile1 = new File(paramString);
                File[] arrayOfFile = localFile1.listFiles();
                int i = arrayOfFile.length;
                j = 0;
                if (j < i) {
                    File localFile2 = arrayOfFile[j];
                    if (!localFile2.exists()) {
                        break;
                    }
                    localFile2.delete();
                    break;
                }
                if (paramBoolean) {
                    localFile1.delete();
                }
                return true;
            } catch (Exception localException) {
                localException.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * 获取SD卡根路径
     *
     * @return
     */
    public static String getSDCardRoot() {
        if (isSDCardMounted()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return "";
    }

    /**
     * 判断文件是否存在
     *
     * @param filePath 文件路径
     * @return {@code true}: 存在<br>{@code false}: 不存在
     */
    public static boolean isFileExists(String filePath) {
        return isFileExists(getFileByPath(filePath));
    }

    /**
     * 判断文件是否存在
     *
     * @param file 文件
     * @return {@code true}: 存在<br>{@code false}: 不存在
     */
    public static boolean isFileExists(File file) {
        return file != null && file.exists();
    }


    //    /**
    //     * 检测文件是否存在
    //     *
    //     * @param paramString
    //     * @return
    //     */
    //    public static boolean isFileExists(String paramString) {
    //        if (!TextUtils.isEmpty(paramString)) {
    //            return new File(paramString).exists();
    //        }
    //        throw new RuntimeException("Path is empty");
    //    }

    private static boolean isSDCardMounted() {
        return "mounted".equals(Environment.getExternalStorageState());
    }


    /**
     * 写入文件
     *
     * @param paramString1
     * @param paramString2
     */
    public static void write2File(String paramString1, String paramString2) {
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(new File(paramString1), true)));
            out.write(paramString2 + "\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取当前图片
     *
     * @return
     */
    public static File getImg(byte[] imgByte, int width, int height) {
        ByteArrayOutputStream localByteArrayOutputStream = null;
        try {
            if (imgByte == null) {
                return null;
            }
            YuvImage localYuvImage = new YuvImage(imgByte, 17, width, height, null);
            localByteArrayOutputStream = new ByteArrayOutputStream();
            localYuvImage.compressToJpeg(new Rect(0, 0, localYuvImage.getWidth(), localYuvImage.getHeight()), 50, localByteArrayOutputStream);
            File localFile = saveFacePic(BitmapFactory.decodeByteArray(localByteArrayOutputStream.toByteArray(), 0, localByteArrayOutputStream.toByteArray().length));
            return localFile;
        } catch (Exception localException) {
            localException.printStackTrace();
        } finally {
            try {
                if (localByteArrayOutputStream != null) {
                    localByteArrayOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取当前图片
     *
     * @return
     */
    public static byte[] getImgToByte(byte[] imgByte, Rect rect, int width, int height) {
        ByteArrayOutputStream localByteArrayOutputStream = null;
        try {
            if (imgByte == null) {
                return null;
            }
            YuvImage localYuvImage = new YuvImage(imgByte, ImageFormat.NV21, width, height, null);
            localByteArrayOutputStream = new ByteArrayOutputStream();
            localYuvImage.compressToJpeg(rect, 50, localByteArrayOutputStream);
            return localByteArrayOutputStream.toByteArray();
        } catch (Exception localException) {
            localException.printStackTrace();
        } finally {
            try {
                if (localByteArrayOutputStream != null) {
                    localByteArrayOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static byte[] file2Bytes(File file) {
        int byte_size = 1024;
        byte[] b = new byte[byte_size];
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
                    byte_size);
            for (int length; (length = fileInputStream.read(b)) != -1; ) {
                outputStream.write(b, 0, length);
            }
            fileInputStream.close();
            outputStream.close();
            return outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前图片
     *
     * @return
     */
    public static File getImg(byte[] imgByte, Rect rect, int width, int height) {
        ByteArrayOutputStream localByteArrayOutputStream = null;
        try {
            if (imgByte == null) {
                return null;
            }
            YuvImage localYuvImage = new YuvImage(imgByte, ImageFormat.NV21, width, height, null);
            localByteArrayOutputStream = new ByteArrayOutputStream();
            localYuvImage.compressToJpeg(rect, 100, localByteArrayOutputStream);
            File localFile = saveFacePic(BitmapFactory.decodeByteArray(localByteArrayOutputStream.toByteArray(), 0, localByteArrayOutputStream.toByteArray().length));
            return localFile;
        } catch (Exception localException) {
            localException.printStackTrace();
        } finally {
            try {
                if (localByteArrayOutputStream != null) {
                    localByteArrayOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 保存图片
     *
     * @param paramBitmap
     * @return
     */
    public static File saveFacePic(Bitmap paramBitmap) {
        try {
            StringBuilder localStringBuilder = new StringBuilder();
            localStringBuilder.append(getSDCardRoot());
            localStringBuilder.append(Config.PHOTO_PATH);
            File localFile = new File(localStringBuilder.toString(), System.currentTimeMillis() + ".jpg");
            deleteFile(localFile.getAbsolutePath());
            BufferedOutputStream localBufferedOutputStream = new BufferedOutputStream(new FileOutputStream(localFile));
            paramBitmap.compress(Bitmap.CompressFormat.JPEG, 80, localBufferedOutputStream);
            localBufferedOutputStream.flush();
            localBufferedOutputStream.close();
            return localFile;
        } catch (Exception localException) {
            localException.printStackTrace();
        }
        return null;
    }

    /**
     * 把字节数组保存为一个文件
     *
     * @Author HEH
     * @EditTime 2010-07-19 上午11:45:56
     */
    public static File getFileFromBytes(byte[] b) {
        BufferedOutputStream stream = null;
        File file = null;
        try {
            StringBuilder localStringBuilder = new StringBuilder();
            localStringBuilder.append(getSDCardRoot());
            localStringBuilder.append(Config.PHOTO_PATH);
            file = new File(localStringBuilder.toString(), System.currentTimeMillis() + ".jpg");
            FileOutputStream fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return file;
    }


    /**
     * 删除单个文件
     *
     * @param paramString
     * @return
     */
    public static boolean deleteFile(String paramString) {
        if (!TextUtils.isEmpty(paramString)) {
            File localFile = new File(paramString);
            if (localFile.exists()) {
                try {
                    localFile.delete();
                    return true;
                } catch (Exception localException) {
                    localException.printStackTrace();
                }
            }
            return false;
        }
        throw new RuntimeException("Path is empty");
    }


    /**
     * 删除文件夹及目录下所有文件
     *
     * @param file
     */
    public static void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 获取文件名称
     *
     * @param paramString
     * @param paramBoolean
     * @return
     */
    public static String getFileName(String paramString, boolean paramBoolean) {
        int i = paramString.lastIndexOf("/");
        int j = paramString.lastIndexOf(".");
        if ((i != -1) && (j != -1)) {
            if (paramBoolean) {
                return paramString.substring(i + 1, paramString.length());
            }
            return paramString.substring(i + 1, j);
        }
        return "";
    }

    public static String getFileNameNoEx(String paramString) {
        if ((paramString != null) && (paramString.length() > 0)) {
            int i = paramString.lastIndexOf('.');
            if ((i > -1) && (i < paramString.length())) {
                return paramString.substring(0, i);
            }
        }
        return paramString;
    }

    public static String getFilePathFromUri(Context paramContext, Uri paramUri) {
        if ("content".equals(paramUri.getScheme())) {
            String[] arrayOfString = {"_data"};
            Cursor localCursor = paramContext.getContentResolver().query(paramUri, arrayOfString, null, null, null);
            localCursor.moveToFirst();
            String str = localCursor.getString(localCursor.getColumnIndex(arrayOfString[0]));
            localCursor.close();
            return str;
        }
        if ("file".equals(paramUri.getScheme())) {
            return new File(paramUri.getPath()).getAbsolutePath();
        }
        return null;
    }


    /**
     * 获取视频文件截图
     *
     * @param path 视频文件的路径
     * @return Bitmap 返回获取的Bitmap
     */

    public static Bitmap getVideoThumb(String path) {

        MediaMetadataRetriever media = new MediaMetadataRetriever();

        media.setDataSource(path);

        return media.getFrameAtTime();

    }

    /**
     * 获取视频的缩略图
     * 先通过ThumbnailUtils来创建一个视频的缩略图，然后再利用ThumbnailUtils来生成指定大小的缩略图。
     * 如果想要的缩略图的宽和高都小于MICRO_KIND，则类型要使用MICRO_KIND作为kind的值，这样会节省内存。
     *
     * @param videoPath 视频的路径
     * @param width     指定输出视频缩略图的宽度
     * @param height    指定输出视频缩略图的高度度
     * @param kind      参照MediaStore.Images(Video).Thumbnails类中的常量MINI_KIND和MICRO_KIND。
     *                  其中，MINI_KIND: 512 x 384，MICRO_KIND: 96 x 96
     * @return 指定大小的视频缩略图
     */
    public static Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind) {
        Bitmap bitmap = null;
        // 获取视频的缩略图
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind); //調用ThumbnailUtils類的靜態方法createVideoThumbnail獲取視頻的截圖；
        if (bitmap != null) {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);//調用ThumbnailUtils類的靜態方法extractThumbnail將原圖片（即上方截取的圖片）轉化為指定大小；
        }
        return bitmap;
    }


    public static void copyFromAssets(AssetManager assets, String sourceFilename, String newPath, boolean isCover)
            throws IOException {
        File file = new File(newPath);
        if (isCover || (!isCover && !file.exists())) {
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = assets.open(sourceFilename);
                fos = new FileOutputStream(file.getPath());
                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = is.read(buffer, 0, 1024)) >= 0) {
                    fos.write(buffer, 0, size);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } finally {
                        if (is != null) {
                            is.close();
                        }
                    }
                }
            }
        }
    }

    /**
     * 遍历文件夹下的所有文件
     *
     * @param fileAbsolutePath
     * @return
     */
    public static List<File> getAllFileToDir(String fileAbsolutePath) {
        List<File> files = new ArrayList<>();
        //        Vector<String> vecFile = new Vector<String>();
        File file = new File(fileAbsolutePath);

        File[] subFile = file.listFiles();
        if (subFile != null) {
            for (File file1 : subFile) {
                // 判断是否为文件夹
                if (file1.isFile()) {
                    files.add(file1);
                }
            }
        }
        return files;
    }

    //    public static String saveBitmap(View view) {
    //        if (view == null)
    //            return "";
    //        view.setDrawingCacheEnabled(true);
    //        Bitmap secondBitmap = getBitmapByView(view);
    //        view.setDrawingCacheEnabled(false);
    //        Bitmap bitmap = Bitmap.createBitmap(secondBitmap.getWidth()
    //                , secondBitmap.getHeight(), secondBitmap.getConfig());
    //        Canvas canvas = new Canvas(bitmap);
    //        canvas.drawBitmap(secondBitmap, new Matrix(), null);
    //
    //        //        // 可能部分手机需要分开创建文件夹
    //        //        String dzxc = Environment.getExternalStorageDirectory() + "/dzxc";
    //        //        String dzxc_photo = dzxc + "/photo";
    //        //        File appDir = new File(dzxc);
    //        //        if (!appDir.exists()) {
    //        //            appDir.mkdir();
    //        //        }
    //
    //        File appDir_photo = new File(FileUtils.getSDCardRoot() + Config.PHOTO_PATH);
    //        if (!appDir_photo.exists()) {
    //            appDir_photo.mkdir();
    //        }
    //        String fileName = System.currentTimeMillis() + ".jpg";
    //        File file = new File(appDir_photo, fileName);
    //        try {
    //            FileOutputStream fos = new FileOutputStream(file);
    //            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    //            fos.flush();
    //            fos.close();
    //        } catch (FileNotFoundException e) {
    //            e.printStackTrace();
    //        } catch (IOException e) {
    //            e.printStackTrace();
    //        }
    //        return file.getAbsolutePath();
    //    }

    public static Bitmap getBitmapByView(View view) {
        int h = 0;
        Bitmap bitmap;
        h += view.getHeight();
        bitmap = Bitmap.createBitmap(view.getWidth(), h,
                Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }


    public static Bitmap mergeBitmap(Bitmap backBitmap, Bitmap frontBitmap) {

        if (backBitmap == null || backBitmap.isRecycled()
                || frontBitmap == null || frontBitmap.isRecycled()) {
            //            Log.e(TAG, "backBitmap=" + backBitmap + ";frontBitmap=" + frontBitmap);
            return null;
        }
        Bitmap bitmap = backBitmap.copy(Bitmap.Config.ARGB_8888, true);
        Canvas canvas = new Canvas(bitmap);
        Rect baseRect = new Rect(0, 0, backBitmap.getWidth(), backBitmap.getHeight());
        Rect frontRect = new Rect(0, 0, frontBitmap.getWidth(), frontBitmap.getHeight());
        canvas.drawBitmap(frontBitmap, frontRect, baseRect, null);
        backBitmap.recycle();
        backBitmap = null;
        frontBitmap.recycle();
        frontBitmap = null;
        return bitmap;
    }

    /**
     * 获取文件大小
     *
     * @param filePath 文件路径
     * @return 文件大小
     */
    public static String getFileSize(String filePath) {
        return getFileSize(getFileByPath(filePath));
    }

    /**
     * 根据文件路径获取文件
     *
     * @param filePath 文件路径
     * @return 文件
     */
    public static File getFileByPath(String filePath) {
        return TextUtils.isEmpty(filePath) ? null : new File(filePath);
    }

    /**
     * 获取文件大小
     * <p>例如：getFileSize(file, RxConstTool.MB); 返回文件大小单位为MB</p>
     *
     * @param file 文件
     * @return 文件大小
     */
    public static String getFileSize(File file) {
        if (!isFileExists(file.getAbsolutePath())) {
            return "";
        }
        return byte2FitSize(file.length());
    }

    /**
     * 字节数转合适大小
     * <p>保留3位小数</p>
     *
     * @param byteNum 字节数
     * @return 1...1024 unit
     */
    public static String byte2FitSize(long byteNum) {
        if (byteNum < 0) {
            return "shouldn't be less than zero!";
        } else if (byteNum < 1024) {
            return String.format(Locale.getDefault(), "%.3fB", (double) byteNum);
        } else if (byteNum < 1048576) {
            return String.format(Locale.getDefault(), "%.3fKB", (double) byteNum / 1024);
        } else if (byteNum < 1073741824) {
            return String.format(Locale.getDefault(), "%.3fMB", (double) byteNum / 1048576);
        } else {
            return String.format(Locale.getDefault(), "%.3fGB", (double) byteNum / 1073741824);
        }
    }

    public final void addBitmapToAlbum(Bitmap bitmap, String displayName, String mimeType, Bitmap.CompressFormat compressFormat,
                                       ContentResolver contentResolver) {
        ContentValues values = new ContentValues();
        values.put("_display_name", displayName);
        values.put("mime_type", mimeType);
        if (Build.VERSION.SDK_INT >= 29) {
            values.put("relative_path", Environment.DIRECTORY_DCIM);
        } else {
            StringBuilder var10002 = new StringBuilder();
            File var10003 = Environment.getExternalStorageDirectory();
            values.put("_data", var10002.append(var10003.getPath()).append('/').append(Environment.DIRECTORY_DCIM).append('/').append(displayName).toString());
        }

        Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        if (uri != null) {
            OutputStream outputStream = null;
            try {
                outputStream = contentResolver.openOutputStream(uri);
                if (outputStream != null) {
                    bitmap.compress(compressFormat, 100, outputStream);
                    outputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }
}